class SalesController < ApplicationController
  # before_action :set_sale, only: [:show, :edit, :update, :destroy]
  load_and_authorize_resource

  respond_to :html, :json

  def index
    if params[:q].blank? || (params[:q]['sold_at_gteq'].blank? && params[:q]['sold_at_lteq'].blank?)
      params[:q] ||= {}
      params[:q]['sold_at_gteq'] = 1.month.ago.strftime('%F')
      params[:q]['sold_at_lteq'] = Date.current.strftime('%F')
    end

    @q = Sale.ransack(params[:q])
    @sales = @q.result.page(params[:page])
    respond_with(@sales)
  end

  def show
    @versions = PaperTrail::Version.where(item_type: Sale, item_id: @sale.id).order('created_at DESC').limit 6
    respond_with(@sale)
  end

  def new
    @sale = Sale.new(sold_at: Date.current)
    respond_with(@sale)
  end

  def edit
  end

  def create
    @sale = Sale.new(sale_params)
    @sale.save
    respond_with(@sale)
  end

  def update
    @sale.update(sale_params)
    respond_with(@sale)
  end

  def destroy
    @sale.destroy
    respond_with(@sale)
  end

  def top10
    @total_number = Sale.month(Date.current).sum('product_number')
    @total_price = Sale.month(Date.current).joins(:product).sum('sales.product_number * products.price')
    @top10_salers = Sale.month(Date.current).select('user_id, sum(sales.product_number) as total_number, sum(sales.product_number * products.price) total_price')
                       .joins(:product).group('sales.user_id').order('total_price DESC').limit 10
  end

  def by_me
    @sales = Sale.where(user_id: current_user.id).page(params[:page])
  end

  private
    def set_sale
      @sale = Sale.find(params[:id])
    end

    def sale_params
      params.require(:sale).permit(:sold_at, :user_id, :product_id, :customer_id, :product_number, :sales_reward, :change_explain)
    end
end
